home *** CD-ROM | disk | FTP | other *** search
/ Monster Media 1996 #15 / Monster Media Number 15 (Monster Media)(July 1996).ISO / prog_d / aspell22.zip / MEMOCK32.PAS < prev    next >
Pascal/Delphi Source File  |  1996-04-03  |  22KB  |  430 lines

  1. unit Memock32;
  2.  
  3. interface
  4.  
  5. { Revisions:
  6.     01/02/96 - Corrected SyncBuffer.  It was not getting the last
  7.                character in the TMemo's buffer.
  8.     01/07/96 - Improved handling of hyphenated words.
  9.     01/09/96 - Added Orpheus Editor component.
  10.     01/11/96 - Added Selection spell checking methods.
  11.     01/12/96 - Improved the look of the suggestion dialog box.
  12.     01/16/96 - Renamed TMemoSpellCheck to TMemoSpell.
  13.     03/15/96 - Converted to 32-Bit component for Delphi 2.0
  14. }
  15.  
  16. uses
  17.   Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  18.   StdCtrls, ComCtrls, DBCtrls, SugDlg32;
  19.  
  20. const SpellCharSet : set of char =
  21.        ['A'..'Z','a'..'z',#138,#140,#159,#192..#214,
  22.         #216..#223,#240,#154,#156,#224..#239,#241..#246,#248..#255];
  23.  
  24.  
  25. type SuggestionType = (stNoSuggest, stCloseMatch, stPhoneme);
  26.  
  27. type
  28.   TMemoSpell = class(TComponent)
  29.   private
  30.     { Private declarations }
  31.     FSuggestType         : SuggestionType;  { Holds the default initial suggestion type }
  32.     FDictionaryMain      : string;          { Holds the name of the main dictionary file }
  33.     FDictionaryUser      : string;          { Holds the name of the user's custom dictionary file }
  34.     FSuggestMax          : byte;            { Holds the maximum number of suggestions to return }
  35.     UserDictID           : integer;         { Holds the ID number ofhte open user dictionary }
  36.     FLeaveDictionaryOpen : boolean;         { Should we leave the dictionary files open? }
  37.     FDictionaryOpen      : boolean;         { Is the dictionary open? }
  38.     FAvoidHighlight      : boolean;         { Should the dialog avoid the highlighted text? }
  39.   protected
  40.     { Protected declarations }
  41.     DictDataPtr   : pointer;               { Pointer to internal dictionary data }
  42.     SuggestDlg    : TSugDialog;            { The dialog box for this component }
  43.     StartWord     : string;                { Temporary place to store the word being tested }
  44.     IgnoreList    : TStringList;           { List of words to ignore }
  45.     ReplaceList   : TStringList;           { Replacement word list }
  46.     AlternateList : TStringList;           { Replacement word alternate word list }
  47.     procedure BaseCheckMemo(var TheMemo : TMemo; CheckStart, CheckLength : integer);
  48.     procedure SetDialogPosition(var TheMemo : TMemo);
  49.   public
  50.     { Public declarations }
  51.     UserDictionaryOpen : boolean;                 { Record if the custom user dictionary was opened ok }
  52.     constructor Create(AOwner : TComponent); override;  { Standard create method }
  53.     procedure Free;                        { Standard free method }
  54.     procedure SetMaximumSuggestions(Max : byte);      { Method to set the maximum number of suggestions }
  55.     procedure SetDictionaryMain(Filename : string);   { Set a new main dictionary filename }
  56.     procedure SetDictionaryUser(Filename : string);   { Set a new user dictionary filename }
  57.     property DictionaryOpen : boolean read FDictionaryOpen;
  58.  published
  59.     { Published declarations }
  60.     procedure CheckMemo(TheMemo : TMemo);      { Main method, check the spelling of a TMemo }
  61.     procedure CheckMemoSelection(TheMemo : TMemo); { Alternate method, check the selected text only }
  62.     procedure CheckDBMemo(TheMemo : TDBMemo);  { Main method, check the spelling of a TDBMemo }
  63.     procedure CheckDBMemoSelection(TheMemo : TDBMemo);  { Alternate method, check the selected text only }
  64.     procedure ClearLists;                      { Method to clear the ignore/replace lists }
  65.     property SuggestType : SuggestionType read FSuggestType write FSuggestType default stCloseMatch;
  66.        { Get/Set the initial suggestion type }
  67.     property DictionaryMain : string read FDictionaryMain write SetDictionaryMain;
  68.        { Get/Set the name of the main dictionary file }
  69.     property DictionaryUser : string read FDictionaryUser write SetDictionaryUser;
  70.        { Get/Set the name of the user dictionary file }
  71.     property MaxSuggestions : byte read FSuggestMax write SetMaximumSuggestions default 10;
  72.        { Get/Set the maximum number of suggestions }
  73.     property LeaveDictionariesOpen : boolean read FLeaveDictionaryOpen write FLeaveDictionaryOpen default TRUE;
  74.        { Get/Set whether the dictionary should be opened/closed after each call }
  75.     property AvoidHighlight : boolean read FAvoidHighlight write FAvoidHighlight default true;
  76.        { Get/Set whether the highlight should be avoided by the dialog }
  77.   end;
  78.  
  79.  
  80. procedure Register;
  81.  
  82. implementation
  83.  
  84. uses BsASpl32;
  85.  
  86.  
  87. procedure Register;  { Standard component registration procedure }
  88. begin
  89.   RegisterComponents('Samples', [TMemoSpell]);
  90. end;
  91.  
  92.  
  93. constructor TMemoSpell.Create(AOwner : TComponent);
  94. { Standard create method }
  95. begin
  96.   inherited Create(AOwner);           { Make sure the base component to made }
  97.   FSuggestType := stCloseMatch;       { Set the default values }
  98.   FDictionaryMain := 'acrop.dct';
  99.   FDictionaryUser := 'custom.dct';
  100.   FLeaveDictionaryOpen := TRUE;
  101.   FDictionaryOpen  := FALSE;
  102.   UserDictionaryOpen := FALSE;
  103.   FSuggestMax     := 10;
  104.   FAvoidHighlight := true;
  105.   IgnoreList := TStringList.Create;    { Create the list of ignored words }
  106.   IgnoreList.Clear;                    { And set it to the way it is needed to be }
  107.   IgnoreList.Sorted := TRUE;
  108.   ReplaceList := TStringList.Create;   { Create the list of words to replace }
  109.   ReplaceList.Clear;                   { And set it up }
  110.   ReplaceList.Sorted := FALSE;
  111.   AlternateList := TStringList.Create; { Create the list of words to replace with }
  112.   AlternateList.Clear;                 { And set it up }
  113.   AlternateList.Sorted := FALSE;
  114.   InitDictionaryData(DictDataPtr);        { Create the internal dictionary data }
  115.   SuggestDlg := TSugDialog.Create(Self);  { Create the dialog box }
  116.   SuggestDlg.DictDataPtr := DictDataPtr;  { And let it know the internal data address }
  117. end;
  118.  
  119. procedure TMemoSpell.Free;
  120. { Standard free method }
  121. begin
  122.   if FDictionaryOpen then
  123.     BsASpl32.CloseDictionaries(DictDataPtr);
  124.   ReleaseDictionaryData(DictDataPtr);
  125.   IgnoreList.Free;     { Get rid of the ignore list }
  126.   ReplaceList.Free;    { Get rid of the replacement list }
  127.   AlternateList.Free;  { Get rid of the replacement word list }
  128.   SuggestDlg.Free;     { Get rid of the suggestion dialog box }
  129.   inherited Free;      { and then the base component }
  130. end;
  131.  
  132. procedure TMemoSpell.SetMaximumSuggestions(Max : byte);
  133. { Set the maximum number of suggestions to return }
  134. begin
  135.   FSuggestMax := Max;   { And store the value }
  136. end;
  137.  
  138. procedure TMemoSpell.SetDictionaryMain(Filename : string);
  139. begin
  140.   if FDictionaryOpen or UserDictionaryOpen then
  141.     begin
  142.       BsASpl32.CloseDictionaries(DictDataPtr);  { Close the dictionaries since filename is changing }
  143.       FDictionaryOpen := FALSE;                 { Mark them as not opened }
  144.       UserDictionaryOpen := FALSE;
  145.     end;
  146.   FDictionaryMain := Filename;
  147. end;
  148.  
  149. procedure TMemoSpell.SetDictionaryUser(Filename : string);
  150. begin
  151.   if FDictionaryOpen or UserDictionaryOpen then
  152.     begin
  153.       BsASpl32.CloseDictionaries(DictDataPtr);  { Close the dictionaries since filename is changing }
  154.       FDictionaryOpen := FALSE;                 { Mark them as not opened }
  155.       UserDictionaryOpen := FALSE;
  156.     end;
  157.   FDictionaryUser := Filename;
  158. end;
  159.  
  160. procedure TMemoSpell.ClearLists;
  161. begin
  162.   IgnoreList.Clear;                    { Clear the ignore list }
  163.   IgnoreList.Sorted := TRUE;
  164.   ReplaceList.Clear;                   { Clear the list of words to replace }
  165.   ReplaceList.Sorted := FALSE;
  166.   AlternateList.Clear;                 { Clear the list of words to do the replacing with }
  167.   AlternateList.Sorted := FALSE;
  168. end;
  169.  
  170. procedure TMemoSpell.SetDialogPosition(var TheMemo : TMemo);
  171. { Set the position of the Suggestion Dialog based on the current line.
  172.   If the dialog window and the editor area do not overlap, or there is no
  173.   possibility of the highlight being covered don't move it. }
  174. var EditorScreen : TPoint;
  175.     SelectBottom : longint;
  176.     SelectTop    : longint;
  177.     SelectPoint  : longint;
  178.     SelectPos    : longint;
  179. begin
  180.   EditorScreen := TheMemo.ClientToScreen(TheMemo.ClientRect.TopLeft);
  181.   if ((EditorScreen.X+TheMemo.Width) < SuggestDlg.Left) or
  182.      (EditorScreen.X > (SuggestDlg.Left+SuggestDlg.Width)) or
  183.      ((EditorScreen.Y+TheMemo.Height) < SuggestDlg.Top) or
  184.      (EditorScreen.Y > (SuggestDlg.Top+SuggestDlg.Height)) then
  185.     exit;  { Not in editor area so exit without bothering to move the dialog }
  186.   { Figure out where the current line really is on the screen }
  187.   SelectPos := SendMessage(TheMemo.Handle, EM_LINEINDEX, $FFFF, 0);
  188.   SelectPoint := SendMessage(TheMemo.Handle, EM_POSFROMCHAR, SelectPos, 0);
  189.   SelectTop := (SelectPoint SHR 16) + EditorScreen.Y;     { Get Position of selection on screen }
  190.   SelectBottom := SelectTop + TheMemo.Font.Size + 3;
  191.   { See if the highlight could actually be covered by the dialog }
  192.   if (SelectBottom  < SuggestDlg.Top) or
  193.      (SelectTop > (SuggestDlg.Top+SuggestDlg.Height)) then
  194.     exit;  { Not near the highlight, exit without moving }
  195.   { It could be covering the highlight, so move to the top or bottom of screen }
  196.   if SelectBottom > (Screen.Height div 2) then
  197.     SuggestDlg.Top := 20
  198.   else
  199.     SuggestDlg.Top := Screen.Height-SuggestDlg.Height-20;
  200. end;
  201.  
  202. procedure TMemoSpell.BaseCheckMemo(var TheMemo : TMemo; CheckStart, CheckLength : integer);
  203. { The main method for this component.  Test the spelling of the text in the passed memo }
  204. type LargeBuffer = array[0..$FFFF] of char; { 64K - the limit on memo's size }
  205.      LargeBufferPtr = ^LargeBuffer;
  206. var Done       : boolean;        { Loop control }
  207.     OldHide    : boolean;        { Storage for the original state of the HideSelection property }
  208.     Changed    : boolean;        { Was anything in the memo changed? }
  209.     EmptyList  : TStringList;    { Empty list in case user dictionary need to be made }
  210.     HoldBuffer : LargeBufferPtr; { Buffer to speed up finding words }
  211.     Start      : integer;        { Start of the word }
  212.     WordEnd    : integer;        { End of the word }
  213.     CheckLoc   : integer;        { Location we are currently checking }
  214.     TheResult  : integer;        { Temporary ShowModal return storage }
  215.   procedure SyncBuffer;
  216.   { Duplicate the memo's text into the temporary buffer }
  217.   begin
  218.     TheMemo.GetTextBuf(HoldBuffer^, TheMemo.GetTextLen+1);
  219.     { No need to worry about the length.  TMemo buffers are 32K or smaller }
  220.   end;
  221.   function GetNextWord : string;
  222.   { Get the next word in the memo }
  223.   var CurrentTextLen    : integer;  { Temporary to hold length of memo's text }
  224.       CurrentPos        : integer;
  225.       S                 : string;
  226.   begin
  227.     { Scan until we find the start of a word.  Defined as someting starting with a letter }
  228.     CurrentTextLen := TheMemo.GetTextLen;  { Just to speed things up a litte }
  229.     CurrentPos := CheckLoc;         { Start at the selection }
  230.     while (CurrentPos < CurrentTextLen) and
  231.            (not (HoldBuffer^[CurrentPos] in SpellCharSet)) do  { The english letters and }
  232.                                                                { non-english characters  }
  233.       Inc(CurrentPos);  { Move to the next character }
  234.     Start := CurrentPos;   { Record the actual start of the word }
  235.     { Find the end of the word.  The word ends when a non-letter character }
  236.     { or the character "'" is found.  }
  237.     S := '';
  238.     while (CurrentPos < CurrentTextLen) and
  239.             (HoldBuffer^[CurrentPos] in (SpellCharSet + [''''])) do
  240.       begin
  241.         S := S + HoldBuffer^[CurrentPos];   { Add it to the current word }
  242.         Inc(CurrentPos);  { Move to the next character }
  243.       end;
  244.     WordEnd := CurrentPos;                   { Save the end of the word }
  245.     GetNextWord := S;                        { Return the found word }
  246.   end;
  247. begin
  248.   try
  249.   HoldBuffer := NIL;
  250.   New(HoldBuffer);    { Create a temporary buffer to hold a copy of the memo's text }
  251.   Changed := FALSE;  { Nothing has been changed yet. }
  252.   OldHide := TheMemo.HideSelection;         { Save the old HideSelection property }
  253.   TheMemo.HideSelection := FALSE;           { and make sure selections are shown }
  254.   SuggestDlg.MaxSuggest := FSuggestMax;  { Set the maximum number of suggestions }
  255.   if not FDictionaryOpen then  { Check to see if the dictionary is already open }
  256.     begin
  257.       FDictionaryOpen := BsASpl32.OpenDictionary(DictDataPtr, FDictionaryMain);  { Open the dictionaries }
  258.       if not FDictionaryOpen then
  259.         begin
  260.           MessageDlg('Could not open dictionary', mtError, [mbOK], -1);
  261.           exit;
  262.         end;
  263.       UserDictID := BsASpl32.OpenUserDictionary(DictDataPtr, FDictionaryUser);  { And record if they actually opened }
  264.       if UserDictID < 0 then        { Didn't open so try to make one }
  265.         begin
  266.           EmptyList := TStringList.Create;   { Create and clear to make an empty list }
  267.           EmptyList.Clear;
  268.           UserDictID := BsASpl32.BuildUserDictionary(DictDataPtr, FDictionaryUser, EmptyList);  { Build dictionary }
  269.           EmptyList.Free;  { Free the empty list }
  270.         end;
  271.       UserDictionaryOpen := UserDictID > 0;  { Check to see if dictionary was opened/made }
  272.     end;
  273.   SyncBuffer;  { Load the text into a easy to access buffer }
  274.   with SuggestDlg do  { The suggestion dialog is used a lot so make it easily accessible }
  275.     begin
  276.       TheMemo.SelLength := 0;   { Set up no selection and move to the }
  277.       TheMemo.SelStart := 0;    { start of the section to check }
  278.       CheckLoc := CheckStart;   { Start at the section to spell check }
  279.       SuggestDlg.Caption := 'Suggestions: Scanning...';  { Tell the user we're scanning the text }
  280.       if FAvoidHighlight then  { Calculate a window position if avoiding the highlight }
  281.         begin
  282.           SuggestDlg.Top := (Screen.Height div 2) - (SuggestDlg.Height div 2);  { Position dialog in center of screen }
  283.           SuggestDlg.Left := (Screen.Width div 2) - (SuggestDlg.Width div 2);
  284.           SetDialogPosition(TheMemo);
  285.         end;
  286.       SuggestDlg.WordEdit.Text := '';   { Clear the fields in the dialog window }
  287.       SuggestDlg.SuggestList.Clear;
  288.       SuggestDlg.TheResult := 0;
  289.       SuggestDlg.DisableButtons;        { Disable all but the Cancel button }
  290.       Application.ProcessMessages;      { Give Windows time to draw the window }
  291.       Done := FALSE;            { Assume we aren't done }
  292.       repeat
  293.         StartWord := GetNextWord;       { Get the next word in the memo }
  294.         Application.ProcessMessages;    { Give Windows time to process mouse events }
  295.         IF not BsASpl32.GoodWord(DictDataPtr, StartWord) THEN  { Is the word in the dictionaries? }
  296.           if IgnoreList.IndexOf(Uppercase(StartWord)) = -1 then  { No, is it in the ignore list? }
  297.             begin  { Word not found and not ignored }
  298.               TheMemo.SelStart  := Start;             { Highlight the word }
  299.               TheMemo.SelLength := WordEnd - Start;
  300.               if ReplaceList.IndexOf(Uppercase(StartWord)) = -1 then  { In the replacement list? }
  301.                 begin
  302.                   case FSuggestType of           { Build an inital list of suggestions }
  303.                     stCloseMatch : SuggestList.Items := BsASpl32.SuggestCloseMatch(DictDataPtr, StartWord, FSuggestMax);
  304.                     stPhoneme    : SuggestList.Items := BsASpl32.SuggestPhoneme(DictDataPtr, StartWord, FSuggestMax);
  305.                     stNoSuggest  : SuggestList.Clear;
  306.                   end;
  307.                   TheMemo.SelText := TheMemo.SelText;
  308.                   TheMemo.SelStart  := Start;             { Highlight the word }
  309.                   TheMemo.SelLength := WordEnd - Start;
  310.                   SuggestDlg.TheResult := 0;              { Clear the Dialog result }
  311.                   SuggestDlg.Caption := 'Suggestions';    { Remove "Scanning" from caption }
  312.                   if FAvoidHighlight then                 { Check if the highlight has to be avoided }
  313.                     SetDialogPosition(TheMemo);
  314.                   if not SuggestDlg.Visible then          { If dialog isn't visible, make it so }
  315.                     SuggestDlg.Show;
  316.                   SuggestDlg.EnableButtons;      { Enable all the dialog controls }
  317.                   WordEdit.Text := StartWord;    { Setup the Suggestion dialog }
  318.                   NotWord.Text := StartWord;     { Setup the Word we are checking }
  319.                   SuggestDlg.ActiveControl := BtnIgnore;    { Make the Ignore Button active control }
  320.                   Application.ProcessMessages;   { Allow Windows to update things }
  321.  
  322.                   repeat                            { Give Windows all the time until }
  323.                     Application.ProcessMessages;   { one of the buttons are pressed }
  324.                   until SuggestDlg.TheResult <> 0;
  325.                   SuggestDlg.DisableButtons;    { Disable the buttons }
  326.                   TheResult := SuggestDlg.TheResult;  { Find out what the user did }
  327.                end
  328.               else
  329.                 begin
  330.                   TheResult := 101;  { Fake Replace Button being pressed }
  331.                   WordEdit.Text := AlternateList.Strings[ReplaceList.IndexOf(Uppercase(StartWord))]; { And get the replacement word }
  332.                 end;
  333.                case TheResult of   { Display the suggestion dialog }
  334.                 100 : Done := TRUE;                            { Cancel - end the spell checking }
  335.                 101,
  336.                 105 : begin   { Replace }
  337.                         TheMemo.SelText := WordEdit.Text;        { Replace - replace the word with the correction }
  338.                         Changed := TRUE;
  339.                         SyncBuffer;                              { Resync the temp buffer }
  340.                         WordEnd := TheMemo.SelStart + TheMemo.SelLength;   { Reset the end of word }
  341.                         CheckLength := CheckLength + (Length(WordEdit.Text) - Length(StartWord)); { Adjust ending length }
  342.                         if TheResult = 105 then { Replace all occurences }
  343.                           begin
  344.                             ReplaceList.Add(StartWord);
  345.                             AlternateList.Add(WordEdit.Text);
  346.                           end;
  347.                       end;
  348.                       { Add - the questioned word to the user dictionary }
  349.                 102 : BsASpl32.AddWord(DictDataPtr, StartWord, UserDictID);
  350.                 103 : ; { Ignore just this occurence - Don't do anything }
  351.                 104 : IgnoreList.Add(Uppercase(StartWord));    { Ignore All - add the questioned word to the ignore list }
  352.               end;
  353.             end;
  354.         CheckLoc := WordEnd+1;  { Move to one character after the end of the current word }
  355.       until Done or (CheckLoc >= (CheckLength+CheckStart)) or (SuggestDlg.TheResult = 100);
  356.          { Canceled or end of the memo is reached }
  357.     end;
  358.   if SuggestDlg.Visible then   { Get rid of the dialog, if needed }
  359.     SuggestDlg.Hide;
  360.   if not Changed then    { Let the user know something actually happened }
  361.     MessageDlg('No changes made', mtInformation, [mbOK], -1)
  362.   else
  363.     MessageDlg('Checking complete', mtInformation, [mbOK], -1);
  364.   finally
  365.     Dispose(HoldBuffer);              { Release the temporary buffer }
  366.     if SuggestDlg.Visible then   { Get rid of the dialog, if needed }
  367.       SuggestDlg.Hide;
  368.     if not FLeaveDictionaryOpen then  { Check if the dictionaries should be closed }
  369.       begin
  370.         BsASpl32.CloseDictionaries(DictDataPtr);       { Close the dictionaries  }
  371.         FDictionaryOpen := FALSE;          { Mark them as not opened }
  372.         UserDictionaryOpen := FALSE;
  373.       end;
  374.     AlternateList.Clear;
  375.     ReplaceList.Clear;
  376.     TheMemo.HideSelection := OldHide; { Restore the HideSelection property of the memo }
  377.   end;
  378. end;
  379.  
  380.  
  381. procedure TMemoSpell.CheckMemo(TheMemo : TMemo);
  382. begin
  383.   BaseCheckMemo(TheMemo, 0, TheMemo.GetTextLen+1);  { Check the whole memo }
  384. end;
  385.  
  386. procedure TMemoSpell.CheckMemoSelection(TheMemo : TMemo);
  387. var CheckStart, CheckLength : integer;
  388. begin
  389.   with TheMemo do
  390.     begin
  391.       if SelLength = 0 then  { Make sure there is something selected }
  392.         exit;                { If not then there is nothing to check }
  393.      { Make sure we have a whole word at the start of the selection }
  394.       CheckStart  := SelStart;   { Get the start of the selection }
  395.       CheckLength := SelLength;  { And the length }
  396.       SelLength := 1;  { Only look at one character at a time }
  397.       while (CheckStart <> 0) and (TheMemo.SelText[1] in SpellCharSet) do
  398.         begin
  399.           Dec(CheckStart);         { Move back another charater }
  400.           Inc(CheckLength);        { and expand the length to check }
  401.           if SelStart <> 0 then
  402.             SelStart := SelStart - 1;   { then look at the charcter before that }
  403.           SelLength := 1;
  404.         end;
  405.      { Now make sure we have a whole word at the end of the selection }
  406.       SelStart := CheckStart + CheckLength;  { Move to the end of the selected text }
  407.       SelLength := 1;  { Look at only a single charater }
  408.       while (SelStart < GetTextLen) and (SelText[1] in SpellCharSet) do
  409.         begin
  410.           Inc(CheckLength);          { Expand the selection length by one character }
  411.           if SelStart < GetTextLen then  { And move to the next if possible }
  412.             SelStart := SelStart + 1;
  413.           SelLength := 1;
  414.         end;
  415.     end;
  416.   BaseCheckMemo(TheMemo, CheckStart, CheckLength);  { Check the selected region }
  417. end;
  418.  
  419. procedure TMemoSpell.CheckDBMemo(TheMemo : TDBMemo);
  420. begin
  421.   CheckMemo(TMemo(TheMemo));
  422. end;
  423.  
  424. procedure TMemoSpell.CheckDBMemoSelection(TheMemo : TDBMemo);
  425. begin
  426.   CheckMemoSelection(TMemo(TheMemo));
  427. end;
  428.  
  429. end.
  430.